// pages/all/pages/examination/examination.js
let timer
let app = getApp();
var r = require('../../../../utils/request.js')
Page({
  data: {
    winHeight: "", //窗口高度
    show: false, //答题卡是否显示


    paperId: '', //id
    paperContent: '', //标题


    currentTab: 0, //预设默认选中的题目索引
    num: 1, //当前习题展示

    list: [],
    checkedList: [],
    date: '00:00', //考试倒计时分钟
    timeUse: 0, //共用时
    examLength:0,//总时长

    isFalse:true,//手动离开页面是否需要提交
  },

  // 滚动切换标签样式
  switchTab: function (e) {
    let tips = this.data.list.length - 1
    if (e.detail.current == tips) {
      wx.showToast({
        title: '已经是最后一题了',
        icon: 'none'
      })
    }

    this.setData({
      currentTab: e.detail.current,
      num: parseInt(e.detail.current) + 1
    });

  },

  // 选择
  choose(e) {
    // console.log(e.target.dataset.num1)
    // console.log(e.target.dataset.num2)
    // console.log(e.target.dataset.type)
    let index1 = e.target.dataset.num1
    let index2 = e.target.dataset.num2
    let type = e.target.dataset.type

    let list = this.data.list
    let checkedList = this.data.checkedList

    // 先判断是否是单选
    if (type == 1) {
      list[index1].option.forEach(item => {
        item.check = false
      });
      list[index1].option[index2].check = true //修改当前题目状态
      checkedList[index1].choose = list[index1].option[index2].answer //当前题目单选选中赋值
    } else if (type == 2) { //判断多选
      list[index1].option[index2].check = !list[index1].option[index2].check //修改当前题目状态
      let datas = []
      list[index1].option.forEach(item2 => { //当前题目多选选中
        if (item2.check == true) {
          datas.push(item2.answer)
        }
      });
      checkedList[index1].choose = datas.toString() //当前题目多选选中赋值
    }
    console.log(checkedList)
    // console.log(list)

    this.setData({
      list: list,
      checkedList: checkedList
    })
  },

  // 提交
  submit() {
    var that = this
    // console.log(this.data.checkedList)
    for (let i = 0; i < this.data.checkedList.length; i++) {
      console.log(this.data.checkedList[i].choose)
      if (!this.data.checkedList[i].choose || this.data.checkedList[i].choose == '') {
        wx.showModal({
          title: '交卷',
          content: '您还有题目未完成，确定交卷吗？',
          success: function (res) {
            if (res.confirm) {
              console.log('确定')
              that.handOver(1)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return
      }
    }
    wx.showModal({
      title: '交卷',
      content: '答题完成，确定交卷吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('确定')
          that.handOver(1)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 交卷
  handOver(num) {
    // console.log(this.data.checkedList)
    // console.log(this.data.paperId)
    var that = this
    // 用时
    let useTime = ''
    if(num == 3){
      useTime = that.getTime(that.data.examLength)
    }else{
      useTime = that.getTime(that.data.timeUse)
    }
    // 获取试题
    r.toPost('/exam/commitExam', {
      userId:wx.getStorageSync('userId'),
      useTimeLength:useTime,
      paperId: that.data.paperId,
      examAnswer: JSON.stringify(that.data.checkedList)
    }, (res) => {
      wx.showToast({
        title: '提交成功',
        icon: 'none'
      })
      if(num == 1){
        that.setData({
          isFalse:false//离开页面不再调用
        })
        setTimeout(function(){
          wx.reLaunch({
            url: '/pages/classroom/classroom',
          })
        },1000)
      }
    })
  },

  // 答题卡
  card() {
    let show = this.data.show
    this.setData({
      show: !show
    })
  },

  onLoad: function (options) {
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 260;
        that.setData({
          winHeight: calc
        });
      }
    });

    // 获取试题
    r.toGet('/exam/examSubject', {
      // paperId: options.id
      paperId: '1433354704351621122'
      
    }, (res) => {
      // console.log(res)
      let list = res.retData.subjectVo

      let checkedList = []
      list.forEach(item => {
        let str = {
          id: item.id,
          choose: ''
        }
        checkedList.push(str)
      });
      // console.log(checkedList)
      this.setData({
        list: list,
        checkedList: checkedList,
        paperContent: res.retData.paperContent,
        paperId: res.retData.paperId,
        examLength:res.retData.examLength * 60
      })
      //定时任务开启
      this.countTime(res.retData.examLength)
    })


  },
  // 倒计时
  countTime(time) {
    var that = this
    var leftTime = parseInt(time) * 60 // 45分钟转化成秒
    var timeUse = 0
    // console.log(leftTime)
    timer = setInterval(() => { //获取当前时间
      timeUse += 1
      leftTime = leftTime - 1
      let h = Math.floor(leftTime / 60 / 60 % 24); //时
      let m = Math.floor(leftTime / 60 % 60); //分
      let s = Math.floor(leftTime % 60); //秒
      if (s < 10) {
        s = "0" + s;
      }
      if (m < 10) {
        m = "0" + m;
      }
      if (h < 10) {
        h = "0" + h;
      }
      let time = h + ':' + m + ':' + s
      that.setData({
        date: time,
        timeUse: timeUse
      })
      if (time == "00:00:00") {
        clearInterval(timer); //清除定时器

        that.handOver(3); //自动提交试卷

        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '考试时间已到，自动提交试卷',
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '/pages/classroom/classroom',
              })
            }
          }
        })
        return
      }
    }, 1000);
  },
  // 秒转时分秒
  getTime(time) {
    let h = Math.floor(time / 60 / 60 % 24); //时
    let m = Math.floor(time / 60 % 60); //分
    let s = Math.floor(time % 60); //秒
    if (s < 10) {
      s = "0" + s;
    }
    if (m < 10) {
      m = "0" + m;
    }
    if (h < 10) {
      h = "0" + h;
    }
    return h + '时' + m + '分' + s + '秒'
  },

  //停止定时器
  onHide: function () {
    clearInterval(timer);
  },
  //停止定时器
  onUnload: function () {
    clearInterval(timer);
    console.log(this.data.checkedList)
    console.log(this.data.paperId)
    if(this.data.isFalse){
      this.handOver(2); //自动提交试卷
    }
    
  }
})